const dayjs = require("dayjs");
const chalk = require("chalk");
const { nanoid } = require("nanoid");
const receptionBill = require("../database/model-reception");
const receptionBillDraft = require("../database/model-reception-draft");
const visitingService = require("./service-visiting");
const vehicleService = require("./service-vehicle");
const instructInfo = {
  application: `<span>{ 接待基础信息</span>
    <div style="text-indent: 100px;">id?: "string", // 新增无id，编辑有id</div>
    <div style="text-indent: 100px;">isDraft?: "0|1 number // 是否草稿"</div>
    <div style="text-indent: 100px;">creater: "code"</div>
    <div style="text-indent: 100px;">address: number[]</div>
    <div style="text-indent: 100px;">receptionFrom: "string"</div>
    <div style="text-indent: 100px;">receptionTo: "string"</div>
    <div style="text-indent: 100px;">receptionCat: "enum"</div>
    <div style="text-indent: 100px;">visitingInstitution: "string"</div>
    <div style="text-indent: 100px;">visitorCount: "number"</div>
    <div style="text-indent: 100px;">visitingPurpose: "string"</div>
    <div style="text-indent: 100px;">accompanyEmployee: code[]</div>
    <div style="text-indent: 100px;">importantVisitors: {}[] // 重要客户喜好"</div>
    <div style="text-indent: 100px;">visitorVehicles: string[] // 来访车辆"</div>
  <div>}</div>`,

  appVehicle: "[] // 车辆服务",
  appVisit: "[] // 参观服务",
  appDining: "[] // 用餐服务",
  appConference: "[] // 会议服务",
  appElectronicScreen: "[] // 电子屏服务",
  appHotel: "[] // 住宿服务",
  appGift: "[] // 礼品服务",
  appDining: "{ inner: [] // 内部用餐, outer: [] //外部用餐 }",
};

const createBillNo = (count, prefix = "BD") =>
  prefix + dayjs().format("YYYYMMDDHHmmss") + (count + 1);
const patchId = (target) =>
  target.forEach((it) => !it.id && (it.id = nanoid()));
const arrayToString = (arr) => {
  if (typeof arr === "number") {
    return arr.toString();
  }
  return arr ? arr.join(",") : null;
};
const arrayToJson = (arr) => (arr ? JSON.stringify(arr) : null);

const Bill = async (ctx) => {
  const input = ctx.request.body;
  const body = typeof input === "string" ? JSON.parse(input) : input;
  const {
    application,
    appVehicle, // 车辆服务
    appVisit, // 参观服务
    appDining, // 用餐服务
    appConference, // 会议服务
    appElectronicScreen, // 电子屏服务
    appHotel, // 住宿服务
    appGift, // 礼品服务
    appDining: { inner, outer } = {}, // 内部用餐 //外部用餐
  } = body;

  // patchId(importantVisitors)
  const { id, billNo, address, importantVisitors, visitorVehicles, receptionFrom, receptionTo } =
    application;

  const operationType = id
    ? { method: "update", text: "更新" }
    : { method: "create", text: "保存" };
  const queryCondition = id ? { where: { id } } : {};
  const getbillNo = (count) => (id ? billNo : createBillNo(count));

  if (!id) {
    delete application.id;
  }
  if (application.isDraft === 1) {
    const { count } = await receptionBillDraft.findAndCountAll();
    const bill = await receptionBillDraft[operationType.method](
      {
        status: -1,
        billNo: getbillNo(count),
        content: JSON.stringify(body),
      },
      queryCondition
    );
    ctx.success({
      billId: bill.id,
      billNo: bill.billNo,
      msg: `草稿已${operationType.text}！`,
    });
  } else {
    const { count } = await receptionBill.findAndCountAll();
    const visitingIds = await visitingService[operationType.method](appVisit);
    const vehicleIds = await vehicleService[operationType.method](appVehicle);

    console.log(chalk.yellow(JSON.stringify(vehicleIds)));
    const bill = await receptionBill[operationType.method](
      {
        status: 0,
        billNo: getbillNo(count),
        ...application,
        receptionFrom,
        receptionTo,
        address: arrayToString(address),
        importantVisitors: arrayToJson(importantVisitors), // 重要客户喜好
        visitorVehicles: arrayToJson(visitorVehicles), // 来访车辆
        appVehicle: arrayToString(vehicleIds), // 车辆服务
        appVisit: arrayToString(visitingIds), // 参观服务
        // appDining, // 用餐服务
        // appConference, // 会议服务
        // appElectronicScreen, // 电子屏服务
        // appHotel, // 住宿服务
        // appGift, // 礼品服务
        // appDining
      },
      queryCondition
    );
    ctx.success({
      billId: bill.id,
      billNo: bill.billNo,
      msg: `单据已${operationType.text}！`,
    });
  }
};
Bill.method = "post";
Bill.mark = "保存或者更新单据";
Bill.body = instructInfo;
module.exports = Bill;
